package com.channel.temperature.collect.ui.activity

import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.widget.LinearLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.channel.temperature.collect.app.base.BaseActivity
import com.channel.temperature.collect.app.ext.LiveDataEvent
import com.channel.temperature.collect.app.ext.initBack
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.CRC16Utils
import com.channel.temperature.collect.app.util.DisplayUtil
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.OfflineBean
import com.channel.temperature.collect.databinding.ActivityOfflineBinding
import com.channel.temperature.collect.ui.viewmodel.OfflineCollectModel
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.base.appContext
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import me.hgj.mvvmhelper.ext.toStartActivity
import java.util.Date


class OfflineCollectActivity : BaseActivity<OfflineCollectModel, ActivityOfflineBinding>() {

    lateinit var dialog: WaitDialog
    override fun initView(savedInstanceState: Bundle?) {
        Log.e("OfflineCollectActivity", "重新刷新")
        mToolbar.initBack("离线采集") {
            finish()
        }
        mViewModel.startReadData.value = false
        mViewModel.canFinished = false
        mViewModel.exceptionAndFinishActivity.value = false
        initListener()

        mViewModel.totalSize.value = 0
        mViewModel.clickDeviceName =
            LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name.toString()
        Log.e("点击连接的设备名称", "点击连接的设备名称 : " + mViewModel.clickDeviceName)
        mViewModel.getparameter()

        mViewModel.taskDeviceName = mmkv.getString(ValueKey.CURRENT_DEVICE_NAME, "").toString()

        mViewModel.taskCurrentName = mmkv.getString(ValueKey.CURRENT_TASK_NAME, "").toString()
//        lifecycleScope.launch {
//            mBind.tips.text =
//                "当前设备（${mViewModel.taskDeviceName}）本地已缓存数据长度 " + OfflineBase.get(
//                    appContext
//                ).offlineDao().queryRoomCountByDeviceName(mViewModel.taskDeviceName) + " 条"
//        }

        mViewModel.currentTimeLong = Date().time / 1000
        Log.e("测试", "测试 " + mViewModel.currentTimeLong)
        updateUI()
    }


    override fun onRequestSuccess() {
//        LiveDataEvent.OfflineConnectSPPDevice.observe(this, Observer {
//            if (LiveDataEvent.OfflineConnectSPPDevice.value?.connect == true) {
//                lifecycleScope.launch {
//                    delay(500)
//                    dialog = WaitDialog.show("请等待")
//                    dialog.onBackPressedListener = OnBackPressedListener {
//                        dialog.doDismiss()
//                        false
//                    }
//                    mViewModel.clickDeviceName = it.bluetoothDevice?.name.toString()
//                    mViewModel.clickDeviceMac = it.bluetoothDevice?.address.toString()
//                    connectDevice(LiveDataEvent.OfflineConnectSPPDevice.value!!.bluetoothDevice as BluetoothDevice)
//                }
//            }
//        })
        mViewModel.exceptionAndFinishActivity.observe(this, Observer {
            lifecycleScope.launch {
                if (it) {
                    ToastUtils.show("非法操作，操作异常码：ArrayIndexOutOfBoundsException")
                    this@OfflineCollectActivity.finish()
                }

            }
        })
        mViewModel.totalSize.observe(this, Observer {
            lifecycleScope.launch {
                if (it != 0) {
                    mBind.tips.text = "已读取总条数 ：" + it
                }

            }
        })
        mViewModel.isTaskOver.observe(this, Observer {
            if (it) {
                mBind.queryOfflieTasks.text = "下载离线数据"
            } else {

            }
        })
        mViewModel.RoomtotalSizeTips.observe(this, Observer {
            mBind.tipsTotalSize.text = it


            mViewModel.startReadData.value = true

        })
        mViewModel.startReadData.observe(this, Observer {
            if (it) {

                resetParam()
                mViewModel.clickType = 12
                mViewModel.readListData.clear()
                mViewModel.readListData = ArrayList<OfflineBean>()

                lifecycleScope.launch() {
                    if (HBluetooth.getInstance().isConnected) {
                        if (mBind.queryOfflieTasks.text.toString() == "下载离线数据") {
                            mViewModel.startCheckTimeOut()
                            mViewModel.isLastPackageData = false

                            mBind.queryOfflieTasks.text = "查询中"
                            lifecycleScope.launch {
                                HBluetooth.getInstance().sender()?.let { it1 ->
                                    var systemInfoString = mmkv.getString(ValueKey.SYSTEM_INFO, "")
                                    if (!systemInfoString.isNullOrEmpty()) {
                                        mViewModel.continueReadCMD = true

                                        mBind.startTime.text = "开始时间" + MyUtil.DateToStr(Date())
                                        mViewModel.currentTimeLong = Date().time / 1000
                                        var deviceName =
                                            mmkv.getString(ValueKey.CURRENT_DEVICE_NAME, "")
                                                .toString()
                                        var taskName =
                                            mmkv.getString(ValueKey.CURRENT_TASK_NAME, "")
                                                .toString()
                                        var taskDec =
                                            mmkv.getString(ValueKey.CURRENT_TASK_DEC, "").toString()
                                        var startTime =
                                            mmkv.getString(ValueKey.COLLECTION_START_TIME, "")
                                        var endTime =
                                            mmkv.getString(ValueKey.COLLECTION_END_TIME, "")
                                        mViewModel.dataResultDesc =
                                            deviceName + "AND" + taskName + "AND" + taskDec + "AND" + startTime + "AND" + endTime
                                        mViewModel.clickType = 12

                                        if (mViewModel.readFlashSize > 0) {
                                            if (mViewModel.readFlashSize > 3072) {
                                                mViewModel.isLastPackageData = false
                                                var cmd =
                                                    "FF55AA000A" + getAddress() + "4101" + mViewModel.currentStartLengthToHex(
                                                        mViewModel.currentStartLength,
                                                        mViewModel.readFlash1
                                                    ) + "0C00"
                                                mViewModel.sendCommonCMD(
                                                    cmd + CRC16Utils.checkCRC(
                                                        MyUtil.hex2Bytes(
                                                            cmd
                                                        )
                                                    )
                                                )
                                            } else if (mViewModel.readFlashSize <= 3072) {
                                                mViewModel.isLastPackageData = true
                                                var cmd =
                                                    "FF55AA000A" + getAddress() + "41010000" + mViewModel.currentStartLengthToHex(
                                                        mViewModel.currentStartLength,
                                                        mViewModel.readFlash1
                                                    ) + MyUtil.numberToHexTwo(
                                                        mViewModel.lastPackageDataSize
                                                    )
                                                mViewModel.sendCommonCMD(
                                                    cmd + CRC16Utils.checkCRC(
                                                        MyUtil.hex2Bytes(
                                                            cmd
                                                        )
                                                    )
                                                )
                                            }
                                        } else {
                                            ToastUtils.show("设备里面暂无数据")
                                        }

                                    } else {
                                        ToastUtils.show("请先读取系统配置参数")
                                    }

                                }
                            }
                        } else {
                            ToastUtils.show("操作中，请勿多次点击")
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
            }
        })

    }

    fun resetParam() {
        mViewModel.packageData = ByteArray(3087)
        mViewModel.isLastPackageData = false
        mViewModel.packageDataLength = 0
        mViewModel.currentStartLength = 0
        mViewModel.continueReadCMD = false
        mViewModel.isTaskOver.value = false
        mViewModel.totalSize.value = 0
        mViewModel.errorListData.clear()
    }

    private fun initListener() {
        HBluetooth.getInstance().setReceiver { dataInputStream, result -> //设备发过来的数据将在这里出现
            Log.e(
                "测试返回数据",
                result.size.toString() + "收到蓝牙设备返回数据 OfflineCollect->" + MyUtil.bytes2Hex(
                    result
                )
            )
            mViewModel.handleBLEResult(result)
        }
    }

//    private fun connectDevice(bluetoothDevice: BluetoothDevice?) {
//        Log.e("connectDevice", "connectDevice    " + bluetoothDevice?.name)
//        HBluetooth.getInstance().connect(bluetoothDevice, object : ConnectCallBack {
//            override fun onConnecting() {
//                Log.e(BLEActivity.TAG, "连接中...")
//                dialog.setMessageContent(LiveDataEvent.OfflineConnectSPPDevice.value?.bluetoothDevice?.name + "连接中...")
//            }
//
//            override fun onConnected(sender: Sender) {
//                Log.e(
//                    BLEActivity.TAG, "连接成功,isConnected:" + HBluetooth.getInstance().isConnected
//                )
//                dialog.setMessageContent("连接成功")
//                ToastUtils.show(LiveDataEvent.OfflineConnectSPPDevice.value?.bluetoothDevice?.name + "连接成功")
//
//                dialog.doDismiss()
//            }
//
//            override fun onDisConnecting() {
//                Log.e(BLEActivity.TAG, "断开连接中...")
//            }
//
//            override fun onDisConnected() {
//                Log.e(
//                    BLEActivity.TAG,
//                    "已断开连接,isConnected:" + HBluetooth.getInstance().isConnected
//                )
//
//                ToastUtils.show(LiveDataEvent.OfflineConnectSPPDevice.value?.bluetoothDevice?.name + "已断开连接")
//                dialog.setMessageContent(LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name + " 已断开连接")
//                dialog.doDismiss()
//            }
//
//            override fun onError(errorType: Int, errorMsg: String) {
//                Log.e(BLEActivity.TAG, "错误类型：$errorType 错误原因：$errorMsg")
//                ToastUtils.show(LiveDataEvent.OfflineConnectSPPDevice.value?.bluetoothDevice?.name + "错误类型：$errorType 错误原因：$errorMsg")
//                dialog.setMessageContent("错误类型：$errorType 错误原因：$errorMsg")
//                dialog.doDismiss()
//            } //低功耗蓝牙才需要BleNotifyCallBack
//            //经典蓝牙可以只调两参方法connect(BluetoothDevice device, ConnectCallBack connectCallBack)
//        })
//    }

    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mBind.queryTasks, mBind.searchData, mBind.searchAllData
        ) {
            when (it) {

                mBind.searchData -> {
                    lifecycleScope.launch {
                        if (HBluetooth.getInstance().isConnected) {
                            if (HBluetooth.getInstance().isConnected) {
//                                mViewModel.resetClickType()
                                var bundle = Bundle()
                                bundle.putString(
                                    "deviceName",
                                    mViewModel.taskDeviceName + "&${mViewModel.currentTimeLong}"
                                )
                                mmkv.putBoolean("isLand",DisplayUtil.getScreenHeight(this@OfflineCollectActivity) < DisplayUtil.getScreenWidth(this@OfflineCollectActivity))
                                bundle.putBoolean(
                                    "isLand",
                                    DisplayUtil.getScreenHeight(this@OfflineCollectActivity) < DisplayUtil.getScreenWidth(this@OfflineCollectActivity)
                                )
                                toStartActivity(OfflineDataActivity::class.java, bundle)
                            } else {
                                ToastUtils.show("请先连接设备后再操作")
                            }

                        } else {
                            ToastUtils.show("请先连接设备后再操作")
                        }
                    }

                }

                mBind.searchAllData -> {
                    toStartActivity(CachedDeviceListActivity::class.java)
                }

                mBind.queryTasks -> {
                    lifecycleScope.launch {
                        if (mBind.queryOfflieTasks.text == "下载离线数据") {
                            if (mViewModel.canDownLoad) {
                                var messageDialog = MessageDialog(
                                    "提示", "请选择读取模式。", "快速读取", "取消", "安全读取"
                                ).setButtonOrientation(LinearLayout.HORIZONTAL)
                                messageDialog.maxWidth =
                                    if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE)
                                        appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
                                messageDialog.show()
                                messageDialog.okButtonClickListener =
                                    OnDialogButtonClickListener { dialog, v ->
                                        Log.e("OnDialogButton", "快速模式")
                                        mViewModel.readMode = 1
                                        if (HBluetooth.getInstance().isConnected) {
                                            HBluetooth.getInstance().sender()?.let { it1 ->
                                                mViewModel.clickType = 9
                                                var cmd =
                                                    "FF55AA000A" + getAddress() + "45010000000000C8"
                                                mViewModel.sendCommonCMD(
                                                    cmd + CRC16Utils.checkCRC(
                                                        MyUtil.hex2Bytes(
                                                            cmd
                                                        )
                                                    )
                                                )
                                            }
                                        } else {
                                            ToastUtils.show("请先连接设备后再操作")
                                        }

                                        false
                                    }
                                messageDialog.cancelButtonClickListener =
                                    OnDialogButtonClickListener { dialog, v ->
                                        Log.e("OnDialogButton", "取消")
                                        false
                                    }
                                messageDialog.otherButtonClickListener =
                                    OnDialogButtonClickListener { dialog, v ->
                                        Log.e("OnDialogButton", "安全模式")
                                        mViewModel.readMode = 2
                                        if (HBluetooth.getInstance().isConnected) {
                                            HBluetooth.getInstance().sender()?.let { it1 ->
                                                mViewModel.clickType = 9
                                                var cmd =
                                                    "FF55AA000A" + getAddress() + "45010000000000C8"
                                                mViewModel.sendCommonCMD(
                                                    cmd + CRC16Utils.checkCRC(
                                                        MyUtil.hex2Bytes(
                                                            cmd
                                                        )
                                                    )
                                                )
                                            }
                                        } else {
                                            ToastUtils.show("请先连接设备后再操作")
                                        }

                                        false
                                    }
                            } else {
                                ToastUtils.show("获取数据计算参数失败，请退出界面重新操作")
                            }

                        } else if (mBind.queryOfflieTasks.text == "查询中") {
                            ToastUtils.show("设备操作中，请勿重复点击")
                        }
                    }
                }

            }
        }
    }

    private fun getAddress(): String {
        return "FA"
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        Log.e("onConfigurationChanged", "onConfigurationChanged 屏幕旋转了")
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mBind.layout.orientation = LinearLayout.HORIZONTAL
            val layoutParams1 = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,  // 宽度
                LinearLayout.LayoutParams.WRAP_CONTENT,  // 高度
                1.0f // 权重为1，表示将会分配更多的空间给这个视图
            )
            layoutParams1.setMargins(10, 0, 10, 0)
            mBind.queryTasks.layoutParams = layoutParams1
            mBind.searchData.layoutParams = layoutParams1
            mBind.searchAllData.layoutParams = layoutParams1
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            mBind.layout.orientation = LinearLayout.VERTICAL
            val layoutParams1 = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,  // 宽度
                LinearLayout.LayoutParams.WRAP_CONTENT,  // 高度
            )
            layoutParams1.setMargins(0, 10, 0, 10)
            mBind.queryTasks.layoutParams = layoutParams1
            mBind.searchData.layoutParams = layoutParams1
            mBind.searchAllData.layoutParams = layoutParams1
        }
    }

    private fun updateUI() {
        if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mBind.layout.orientation = LinearLayout.HORIZONTAL
            val layoutParams1 = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,  // 宽度
                LinearLayout.LayoutParams.WRAP_CONTENT,  // 高度
                1.0f // 权重为1，表示将会分配更多的空间给这个视图
            )
            layoutParams1.setMargins(10, 0, 10, 0)
            mBind.queryTasks.layoutParams = layoutParams1
            mBind.searchData.layoutParams = layoutParams1
            mBind.searchAllData.layoutParams = layoutParams1
        } else {
            mBind.layout.orientation = LinearLayout.VERTICAL
        }

    }

}